package com.zahb.qadx.ui.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.SparseArrayCompat;

/**
 * MViewHolder
 * Created by zhoudawei on 2017/6/16.
 */

public class MViewHolder {

    private Context mContext;
    private View mConvertView;
    private SparseArrayCompat<View> mViews = new SparseArrayCompat<>();

    private MViewHolder(@NonNull Context context, @NonNull View convertView) {
        mContext = context;
        mConvertView = convertView;
        convertView.setTag(this);
    }

    static MViewHolder getViewHolder(@NonNull Context context, @NonNull LayoutInflater inflater,
                                     @Nullable View convertView, @NonNull ViewGroup parent, @LayoutRes int layoutId) {
        MViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(layoutId, parent, false);
            holder = new MViewHolder(context, convertView);
        } else {
            holder = (MViewHolder) convertView.getTag();
        }
        holder.mConvertView = convertView;
        return holder;
    }

    public Context getContext() {
        return mContext;
    }

    View getConvertView() {
        return mConvertView;
    }

    public <T extends View> T getView(@IdRes int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }
}
